import axios from 'axios'
import { ES_CONFIG } from '@/config/elasticsearch'

export interface TalentConfigDocument {
  id: number
  type: string
  data: any[][]
  timestamp: string
}

const CACHE_KEY = 'talent_config_cache'
const CACHE_TIMESTAMP_KEY = 'talent_config_cache_timestamp'
const CACHE_EXPIRE_TIME = 24 * 60 * 60 * 1000 // 24小时

/**
 * 从缓存中获取数据
 */
const getFromCache = (): { data: any[][] | null, timestamp: string | null } => {
  try {
    const cachedData = localStorage.getItem(CACHE_KEY)
    const cachedTimestamp = localStorage.getItem(CACHE_TIMESTAMP_KEY)
    
    if (!cachedData || !cachedTimestamp) {
      return { data: null, timestamp: null }
    }

    // 检查缓存是否过期
    const timestamp = new Date(cachedTimestamp).getTime()
    const now = new Date().getTime()
    if (now - timestamp > CACHE_EXPIRE_TIME) {
      clearCache()
      return { data: null, timestamp: null }
    }

    return { 
      data: JSON.parse(cachedData),
      timestamp: cachedTimestamp
    }
  } catch (error) {
    console.error('Failed to get from cache:', error)
    return { data: null, timestamp: null }
  }
}

/**
 * 更新缓存
 */
const updateCache = (data: any[][]): void => {
  try {
    localStorage.setItem(CACHE_KEY, JSON.stringify(data))
    localStorage.setItem(CACHE_TIMESTAMP_KEY, new Date().toISOString())
  } catch (error) {
    console.error('Failed to update cache:', error)
  }
}

/**
 * 清除缓存
 */
export const clearCache = (): void => {
  localStorage.removeItem(CACHE_KEY)
  localStorage.removeItem(CACHE_TIMESTAMP_KEY)
}

/**
 * 保存天赋配置到ES
 */
export const esSaveTalentConfig = async (data: any[][]): Promise<void> => {
  try {
    const payload = {
      type: 'talent_config',
      data: data.filter(row => row.some(cell => cell !== null && cell !== '')),
      timestamp: new Date().toISOString()
    }

    const response = await axios.post(
      `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.talentConfig}/_doc`,
      payload,
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (!response.data.result || !['created', 'updated'].includes(response.data.result)) {
      throw new Error('保存失败')
    }

    // 更新缓存
    updateCache(payload.data)
  } catch (error) {
    console.error('Failed to save talent config:', error)
    throw error
  }
}

/**
 * 从ES获取最新的天赋配置
 * @param forceRefresh 是否强制刷新（跳过缓存）
 */
export const esGetLatestTalentConfig = async (forceRefresh: boolean = false): Promise<any[][] | null> => {
  try {
    // 如果不是强制刷新，先尝试从缓存获取
    if (!forceRefresh) {
      const { data: cachedData, timestamp: cachedTimestamp } = getFromCache()
      if (cachedData) {
        console.log('Using cached data from:', cachedTimestamp)
        return cachedData
      }
    }

    // 强制刷新或缓存不存在/已过期，从ES获取
    const response = await axios.post(
      `${ES_CONFIG.baseUrl}/${ES_CONFIG.indices.talentConfig}/_search`,
      {
        size: 1,
        query: {
          term: {
            type: 'talent_config'
          }
        },
        sort: [
          {
            timestamp: 'desc'
          }
        ]
      },
      {
        headers: {
          'Content-Type': 'application/json'
        }
      }
    )

    if (response.data.hits.total.value === 0) {
      return null
    }

    const doc = response.data.hits.hits[0]._source as TalentConfigDocument
    
    // 更新缓存
    updateCache(doc.data)
    
    return doc.data
  } catch (error) {
    console.error('Failed to get latest talent config:', error)
    // 只有在非强制刷新时才尝试使用缓存数据
    if (!forceRefresh) {
      const { data: cachedData } = getFromCache()
      if (cachedData) {
        console.log('Using cached data after ES request failed')
        return cachedData
      }
    }
    throw error
  }
} 